﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Configuration;
using MySql.Data.MySqlClient;
using System.Data;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
using System.Web.Script.Services;

namespace WebApplication1
{
    /// <summary>
    /// Summary description for IBattleship
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    
    public class IBattleship : System.Web.Services.WebService
    {

        [WebMethod]
        public bool login(string username, string password){

            bool is_success = false;

            String connStr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = connStr;
            conn.Open();

            string query = "select count(*) as cnt from bs_user where username='" + username+"' and password='"+password+"';";
            MySqlCommand cmd = new MySqlCommand(query, conn);
            MySqlDataReader reader = cmd.ExecuteReader();

            reader.Read();
            if (reader.GetInt32(0)==1) {
                is_success = true;                 
            }

            reader.Close();
            cmd.Dispose();
            conn.Close();

            return is_success;
        
        }

        [WebMethod]
        public string getUserList()
        {
            string content = "";

            String connStr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = connStr;
            conn.Open();

            string query = "select * from bs_user ";
            MySqlCommand cmd = new MySqlCommand(query, conn);
            MySqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                content += reader.GetString("username") + ",";
                content += reader.GetString("nickname") + ",";
                content += reader.GetString("ip") + ",";
                content += reader.GetString("port") + ",";
                content += reader.GetString("status") + ",";
                content += reader.GetString("win") + ",";
                content += reader.GetString("lose") + ",";
                content += ";";
            }
            reader.Close();
            cmd.Dispose();
            conn.Close();

            return content;

        }

        [WebMethod]
        public void getOnline(string username, string password, string ip,string port)
        {
            String connStr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = connStr;
            conn.Open();

            //change the user's status to online
            string alt_status = "update bs_user set status='1' , ip='"+ip+"', port='"+port+"'  where username='" +username+ "' and password='"+password+"'";

            MySqlCommand cmd = new MySqlCommand(alt_status, conn);
            MySqlDataReader reader = cmd.ExecuteReader();

            reader.Close();
            cmd.Dispose();
            conn.Close();

        }

        [WebMethod]
        public void getOffline(string username,string password)
        {
            String connStr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = connStr;
            conn.Open();

            //change the user's status to offline
            string alt_status = "update bs_user set status='0' where username='" + username + "' and password='" + password + "'";

            MySqlCommand cmd = new MySqlCommand(alt_status, conn);
            MySqlDataReader reader = cmd.ExecuteReader();

            reader.Close();
            cmd.Dispose();
            conn.Close();

        }

        [WebMethod]
        public void updateResult(string username, string password,bool winOrlose)
        {
            String connStr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = connStr;
            conn.Open();

            string alt_status;
            //change the user's status to offline
            if (winOrlose)
            {
                alt_status = "update bs_user set win=win+1 where username='" + username + "' and password='" + password + "'";
            }
            else {
                alt_status = "update bs_user set lose=lose+1 where username='" + username + "' and password='" + password + "'";
            }

            MySqlCommand cmd = new MySqlCommand(alt_status, conn);
            MySqlDataReader reader = cmd.ExecuteReader();

            reader.Close();
            cmd.Dispose();
            conn.Close();

        }


        [WebMethod]
        public string getUserinfo(int userid)
        {
            string content = "";

            String connStr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = connStr;
            conn.Open();

            string query = "select * from bs_user where id='" + userid + "'";

            MySqlCommand cmd = new MySqlCommand(query, conn);
            MySqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                content += reader.GetString("username") + ",";
                content += reader.GetString("nickname") + ",";
                content += reader.GetString("ip") + ",";
                content += reader.GetString("port") + ",";
                content += reader.GetString("status") + ",";
                content += reader.GetString("win") + ",";
                content += reader.GetString("lose") + ",";
            }
            reader.Close();
            cmd.Dispose();
            conn.Close();

            return content;
        }

        [WebMethod]
        public int register(string username, string password, string nickname)
        {
            if (!this.checkUsername(username)) {
                return 6; 
            }

            String connStr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = connStr;
            conn.Open();

            string insert= "insert into bs_user (username,password,nickname) values ('"+username+"','"+password+"','"+nickname+"')";


            MySqlCommand cmd = new MySqlCommand(insert, conn);
            MySqlDataReader reader = cmd.ExecuteReader();


            reader.Close();
            cmd.Dispose();
            conn.Close();

            return 0;
        }

        public bool checkUsername(string username)
        {
            bool can_be_use = false;
            String connStr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = connStr;
            conn.Open();

            string check = "select count(*) from bs_user where username='" + username+"'";


            MySqlCommand cmd = new MySqlCommand(check, conn);
            MySqlDataReader reader = cmd.ExecuteReader();
            
            reader.Read();
            if (reader.GetInt32(0) == 0)
            {
                can_be_use = true;
            }

            reader.Close();
            cmd.Dispose();
            conn.Close();

            return can_be_use;
        }




    protected string SerializeToXml(object o)
          {
              XmlSerializer serializer = new XmlSerializer(o.GetType(), "");
              MemoryStream w = new MemoryStream();
              XmlTextWriter writer = new XmlTextWriter(w, Encoding.Default);
              writer.Formatting = Formatting.None;
              serializer.Serialize((XmlWriter)writer, o);
              writer.Close();
              return Encoding.Default.GetString(w.ToArray())
                  .Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "")
                  .Replace("<?xml version=\"1.0\" encoding=\"gb2312\"?>", "");
          }
  
        protected object DeserializeFromXml(string s, Type t)
          {
              XmlSerializer serializer = new XmlSerializer(t);
              object obj2 = null;
              XmlTextReader xmlReader = new XmlTextReader(s, XmlNodeType.Element, null);
              obj2 = serializer.Deserialize(xmlReader);
              xmlReader.Close();
              return obj2;
          }


    }
}
